import os

import pymysql
from PySide6 import QtCore
from PySide6.QtWebChannel import QWebChannel
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import QMainWindow, QMessageBox, QListWidget, QListWidgetItem, QComboBox

from global_variables import GlobalVariables


class DatabaseSelect(QMainWindow):
    def __init__(self, app):
        super().__init__()
        self.app = app
        self.ui = app.ui

        self.init()

    def init(self):
        self.ui.database_select.currentIndexChanged.connect(self.selected_database_event)
        self.ui.refresh_database_button.clicked.connect(self.refresh_database_button_clicked)

    # 数据库列表填充数据
    def selected_database_fill_data(self, default_database: str):
        list_sys_databases = ['mysql', 'information_schema', 'performance_schema', 'sys']
        all_databases = self.app.mysqldb.show_databases()
        self.ui.database_select: QComboBox

        self.ui.database_select.currentIndexChanged.disconnect(self.selected_database_event)
        list_database = []
        for database in list_sys_databases:
            if database in all_databases:
                list_database.append(database)

        for database in all_databases:
            if database not in list_sys_databases:
                list_database.append(database)

        self.ui.database_select.clear()
        for d in list_database:
            self.ui.database_select.addItem(d)

        self.ui.database_select.currentIndexChanged.connect(self.selected_database_event)

        if default_database in all_databases:
            self.ui.database_select.setCurrentText(default_database)

        if self.ui.database_select.currentIndex() == 0:
            self.selected_database_event(0)

    # 切换数据库事件
    def selected_database_event(self, index: int):
        select_database = self.ui.database_select.itemText(index)
        self.app.mysqldb.select_db(select_database)
        from controllers.table_list import TableList
        self.app.table_list: TableList
        self.app.table_list.table_list_fill_data()
        self.app.tab_sql_query.sync_table_and_column()

    def refresh_database_button_clicked(self):
        self.ui.database_select: QComboBox
        select_database = self.ui.database_select.currentText()
        self.selected_database_fill_data(select_database)
